<template>
  <div class="common-container">
    <div class="common-header">
      <h2>菜单管理</h2>
      <el-button type="primary" @click="handleAdd">新增菜单</el-button>
    </div>

    <div class="menu-content">
      <el-row :gutter="20">
        <!-- 左侧菜单树 -->
        <el-col :span="8">
          <el-card class="common-tree-card">
            <template #header>
              <div class="common-card-header">
                <span>菜单树</span>
                <div>
                  <el-button text @click="refreshMenuTree">刷新</el-button>
                  <el-button text @click="expandAll">展开/折叠</el-button>
                </div>
              </div>
            </template>
            <el-tree
              ref="menuTreeRef"
              :data="menuTree"
              :props="defaultProps"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ data.name }}</span>
                  <span class="node-actions">
                    <el-button text size="small" @click.stop="handleAdd(data)">添加</el-button>
                    <el-button text size="small" @click.stop="handleEdit(data)">编辑</el-button>
                    <el-button text size="small" type="danger" @click.stop="handleDelete(data)">删除</el-button>
                  </span>
                </span>
              </template>
            </el-tree>
          </el-card>
        </el-col>

        <!-- 右侧菜单详情 -->
        <el-col :span="16">
          <el-card v-if="selectedMenu.id" class="common-detail-card">
            <template #header>
              <div class="common-card-header">
                <span>菜单详情</span>
              </div>
            </template>
            <el-form :model="selectedMenu" label-width="100px">
              <el-form-item label="菜单名称">
                <span>{{ selectedMenu.name }}</span>
              </el-form-item>
              <el-form-item label="菜单类型">
                <span>{{ menuTypeMap[selectedMenu.type] }}</span>
              </el-form-item>
              <el-form-item label="菜单图标" v-if="selectedMenu.icon">
                <el-icon><component :is="selectedMenu.icon" /></el-icon>
                <span class="ml-10">{{ selectedMenu.icon }}</span>
              </el-form-item>
              <el-form-item label="路由地址" v-if="selectedMenu.path">
                <span>{{ selectedMenu.path }}</span>
              </el-form-item>
              <el-form-item label="组件路径" v-if="selectedMenu.component">
                <span>{{ selectedMenu.component }}</span>
              </el-form-item>
              <el-form-item label="权限标识" v-if="selectedMenu.permission">
                <span>{{ selectedMenu.permission }}</span>
              </el-form-item>
              <el-form-item label="显示顺序">
                <span>{{ selectedMenu.orderNum }}</span>
              </el-form-item>
              <el-form-item label="是否显示">
                <span>{{ selectedMenu.visible === 1 ? '是' : '否' }}</span>
              </el-form-item>
              <el-form-item label="状态">
                <span>{{ selectedMenu.status === 1 ? '正常' : '停用' }}</span>
              </el-form-item>
              <el-form-item label="创建时间">
                <span>{{ selectedMenu.createTime }}</span>
              </el-form-item>
            </el-form>
          </el-card>
          <el-empty v-else description="请选择菜单" />
        </el-col>
      </el-row>
    </div>

    <!-- 菜单表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuOptions"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            value-key="id"
            placeholder="请选择上级菜单"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单图标" v-if="menuForm.type !== 2">
          <el-input v-model="menuForm.icon" placeholder="请输入菜单图标" />
        </el-form-item>
        <el-form-item label="路由地址" v-if="menuForm.type !== 2" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item label="组件路径" v-if="menuForm.type === 1">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="权限标识" v-if="menuForm.type === 2" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="menuForm.orderNum" :min="0" />
        </el-form-item>
        <el-form-item label="是否显示" v-if="menuForm.type !== 2">
          <el-radio-group v-model="menuForm.visible">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="menuForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="common-dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMenuTree, getMenuById, addMenu, updateMenu, deleteMenu } from '../utils/api'

export default {
  name: 'MenuManagement',
  setup() {
    // 菜单树数据
    const menuTree = ref([])
    const menuTreeRef = ref(null)
    const isExpandAll = ref(false)
    
    // 选中的菜单
    const selectedMenu = ref({})
    
    // 菜单表单对话框
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const menuFormRef = ref(null)
    const menuForm = reactive({
      id: undefined,
      parentId: 0,
      name: '',
      type: 0,
      icon: '',
      path: '',
      component: '',
      permission: '',
      orderNum: 0,
      visible: 1,
      status: 1
    })
    
    // 表单验证规则
    const rules = {
      name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
      path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
      permission: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
      orderNum: [{ required: true, message: '请输入显示顺序', trigger: 'blur' }]
    }
    
    // 菜单类型映射
    const menuTypeMap = {
      0: '目录',
      1: '菜单',
      2: '按钮'
    }
    
    // 树形配置
    const defaultProps = {
      children: 'children',
      label: 'name'
    }
    
    // 菜单选项（用于上级菜单选择）
    const menuOptions = computed(() => {
      const options = [{ id: 0, name: '主目录', children: [] }]
      if (menuTree.value.length > 0) {
        options[0].children = menuTree.value
      }
      return options
    })
    
    // 获取菜单树
    const loadMenuTree = async () => {
      try {
        const response = await getMenuTree()
        menuTree.value = response.data.data
      } catch (error) {
        console.error('获取菜单树失败', error)
      }
    }
    
    // 刷新菜单树
    const refreshMenuTree = () => {
      loadMenuTree()
      selectedMenu.value = {}
    }
    
    // 展开/折叠所有节点
    const expandAll = () => {
      isExpandAll.value = !isExpandAll.value
      menuTreeRef.value.store.nodesMap = {}
      const nodes = menuTreeRef.value.store._getAllNodes()
      nodes.forEach(node => {
        node.expanded = isExpandAll.value
      })
    }
    
    // 点击节点
    const handleNodeClick = async (data) => {
      try {
        const response = await getMenuById(data.id)
        selectedMenu.value = response.data.data
      } catch (error) {
        console.error('获取菜单详情失败', error)
      }
    }
    
    // 新增菜单
    const handleAdd = (data) => {
      resetForm()
      if (data && data.id) {
        menuForm.parentId = data.id
      }
      dialogTitle.value = '新增菜单'
      dialogVisible.value = true
    }
    
    // 编辑菜单
    const handleEdit = (data) => {
      resetForm()
      dialogTitle.value = '编辑菜单'
      const id = data.id || selectedMenu.value.id
      getMenuById(id).then(response => {
        Object.assign(menuForm, response.data.data)
        dialogVisible.value = true
      })
    }
    
    // 删除菜单
    const handleDelete = (data) => {
      const id = data.id || selectedMenu.value.id
      ElMessageBox.confirm('确认删除该菜单吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMenu(id).then(() => {
          ElMessage.success('删除成功')
          if (selectedMenu.value.id === id) {
            selectedMenu.value = {}
          }
          loadMenuTree()
        })
      }).catch(() => {})
    }
    
    // 重置表单
    const resetForm = () => {
      menuForm.id = undefined
      menuForm.parentId = 0
      menuForm.name = ''
      menuForm.type = 0
      menuForm.icon = ''
      menuForm.path = ''
      menuForm.component = ''
      menuForm.permission = ''
      menuForm.orderNum = 0
      menuForm.visible = 1
      menuForm.status = 1
    }
    
    // 提交表单
    const submitForm = () => {
      menuFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (menuForm.id) {
              await updateMenu(menuForm)
              ElMessage.success('修改成功')
            } else {
              await addMenu(menuForm)
              ElMessage.success('新增成功')
            }
            dialogVisible.value = false
            loadMenuTree()
          } catch (error) {
            console.error('保存菜单失败', error)
          }
        }
      })
    }
    
    onMounted(() => {
      loadMenuTree()
    })
    
    return {
      menuTree,
      menuTreeRef,
      selectedMenu,
      dialogVisible,
      dialogTitle,
      menuForm,
      menuFormRef,
      rules,
      menuTypeMap,
      defaultProps,
      menuOptions,
      refreshMenuTree,
      expandAll,
      handleNodeClick,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm
    }
  }
}
</script>

<style scoped>
.common-tree-card,
.common-detail-card {
  height: calc(100vh - 180px);
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-actions {
  display: none;
}

.el-tree-node:hover .node-actions {
  display: inline-block;
}

.ml-10 {
  margin-left: 10px;
}


</style>